package util;

import java.util.Random;

import model.Input;
import model.SimpleSequence;

import org.apache.commons.math3.ode.events.EventHandler;
import org.apache.commons.math3.ode.events.EventHandler.Action;

import optimizers.commons.GAConstants;
import optimizers.ganeat.amplify.*;

public class MyEventHandlerAmplify extends MyEventHandler{

	
	protected int nbrounds = 0;
	protected int curround = 0;
	protected int Alt = 0;
	
	protected boolean altern = true;
	
	
	public Random rnd = new Random();
	
	
	public MyEventHandlerAmplify(Input[] inputs) {
		super(inputs);	//reference to JankenponEventHandler constructor
		this.nbrounds = ConstantsAmply.nbRounds;	//Which round?
	}
	
	

	@Override
	public double g(double t, double[] y) {
		
		if(curround < 2*nbrounds){
			return (value*(this.inputs[0].timeStep-t+1)); 	//judge
		}
		else{
			return (this.value);
		}
	}
	
	public Action eventOccurred(double arg0, double[] arg1, boolean arg2) {
		
		return EventHandler.Action.RESET_STATE;
	}

	@Override
	public void resetState(double t, double[] y) {
	
		if(curround < 2*nbrounds){
			if(altern){
			y[inputs[0].receivingSeq] = inputs[0].ammount;	//produce judge pic
			((SimpleSequence) inputs[0].seq).protectedSequence = true;
			
			curround++;
			//if(t<GAConstants.maxTime-ConstantsAmply.pulseDuration*ConstantsAmply.bufferRatio){
				//System.out.println("Still good");
			inputs[0].timeStep += ConstantsAmply.pulseDuration;
			
			//} else {
				//System.out.println("Didn't work, because t="+t+" and the last time I can is "+(GAConstants.maxTime-ConstantsAmply.pulseDuration*ConstantsAmply.pulseDuration));
			//}
			value = - value;
			} else {
				((SimpleSequence) inputs[0].seq).protectedSequence = false;
				y[inputs[0].receivingSeq] = 0;	//produce judge pic
				
				curround++;
				//if(t<GAConstants.maxTime-ConstantsAmply.pulseDuration*ConstantsAmply.bufferRatio){
					//System.out.println("Still good");
				inputs[0].timeStep += ConstantsAmply.minDowntime+rnd.nextInt( ConstantsAmply.maxDowntime-ConstantsAmply.minDowntime);
				
				//} else {
					//System.out.println("Didn't work, because t="+t+" and the last time I can is "+(GAConstants.maxTime-ConstantsAmply.pulseDuration*ConstantsAmply.pulseDuration));
				//}
				value = - value;
			}
			altern = !altern;
		}
		
	}

	
}